/**	
 * 全局的js
 */
 var common = {
 	'index' : '/',
 	'zTree' : {},
 	/**
 	 * 首页初始化
 	 */
 	'init' : function(has_subject, dir) {
 		//初始化树
 		common.init_tree(has_subject, dir);

 		//注册事件
 		$('#add_subject').on('hidden.bs.modal', function (e) {
 			$('#add_subject .error').html('');
 			$('input').val('');
		})

		$('#submit_suject').click(function(){
			var name   = $('#subject_name').val();
			var dir    = $('#subject_dir').val();
			var module = $('#subject_module').val();
			
			if(name == '') {
				common.dialog_error('输入项目名称');
				return false;
			}
			if(dir == '') {
				common.dialog_error('输入项目目录');
				return false;
			}
			if(module == '') {
				common.dialog_error('输入服务器同步模块');
				return false;
			}

			//提交数据
			var code = 'subject.add';
			var data = {'name':name,'dir':dir,'module':module};

			common.post_data(code, data, function(ret) {
				if(ret.code == 1) {
					$('#add_subject').modal('hide')
					alert('添加成功');
					location.reload();
				} else{
					var msg = ret.msg;
					common.dialog_error(msg);
				}

			});

		})

		$('#clear_select').click(function(){
			$('#select_node').val('');
			common.zTree.checkAllNodes(false);
		});

		$('.subject_remove').click(function(){
			var click = confirm('确定要删除项目吗？');
			if(!click) {
				return false;
			}

			var key = $(this).attr('key');
			var code = 'subject.remove';
			var data = {'key' : key};
			common.post_data(code, data, function(ret){
				if(ret.code != 1) {
					var msg = ret.msg;
					common.dialog_error(msg);
				} else{
					//删除成功，刷新
					$('#mdf_subject').modal('hide')
					alert('删除成功');
					location.reload();
				}
			});
		});

		var rsync_code = function(key, simulate) {
			simulate = parseInt(simulate);

			var codes = $('#select_node').val();
			if(!codes || !key) {
				return false;
			}

			//如果是正式同步，添加确认
			if(simulate == 0) {
				var click = confirm('确定要正式同步吗？');
				if(!click) {
					return false;
				}
			}

			var code = 'subject.rsyncCode';
			var data = {'simulate':simulate,'codes':codes, 'key' : key};
			common.post_data(code, data, function(ret) {
				if(ret.code == 1) {
					$('#rsync_result .show_result').html(ret.data);
				} else{
					var msg = '<span style="color:red;">' + ret.msg + '</span>';
					$('#rsync_result .show_result').html(msg);
				}
			}, function() {
				if(simulate == 1) {
					$('#rsync_result .rsync_type').html('模拟');
					$('#rsync_result .rsync_type').css('color', 'red');
				} else {
					$('#rsync_result .rsync_type').html('正式');
					$('#rsync_result .rsync_type').css('color', 'red');
				}
				$('#rsync_result .show_result').html('数据同步中 ......');
				$('#rsync_result').modal({'backdrop' : 'static'})
			});
		}

		$('.rsync_code').click(function(){
			var simulate = $(this).attr('simulate');
			var key      =  $(this).attr('key');

			//里面都是正式同步
			$('#rsync_result .rsync_repeat').attr('simulate', simulate);
			$('#rsync_result .rsync_repeat').attr('key', key);
			rsync_code(key, simulate);
		})

		$('#rsync_result .rsync_repeat').click(function(){
			var simulate = $(this).attr('simulate');
			var key      =  $(this).attr('key');

			//是不是有强制同步的标志
			var real_sync = $(this).attr('real_sync');
			if(real_sync) {
				simulate = 0;
			}
			
			rsync_code(key, simulate);
		});
		
 	},

 	'dialog_error' : function(error) {
 		if(typeof error == 'undefined') {
 			error = '';
 		}

 		$('#add_subject .error').html(error);
 	},

 	/*
 	* 提交数据
 	* code : subject.add
 	* data : {'name':'', 'root':'', 'target': ''}
 	*
 	*/
 	'post_data' : function(code, data, func, before_func, error_func) {
 		if(typeof code == 'undefined') {
 			return false;
 		}

 		var tmp = code.split('.');
 		if(tmp.length < 2) {
 			return false;
 		}

 		if(!$.isFunction(before_func)) {
 			before_func = function() {}
 		}

 		if(!$.isFunction(error_func)) {
 			error_func = function() {}
 		}

 		var c = tmp[0];
 		var a = tmp[1];
		var url = common.index + c + '/' + a;

		$.ajax({
		  type: 'POST',
		  url: url,
		  data: data,
		  success: function(ret) {
			func(ret);
		  },
		  dataType: 'json',
		  error : error_func,
		  beforeSend : before_func
		});
 	}, 
 	init_tree : function(has_subject, dir) {
 		if(typeof has_subject != 'undefined' && has_subject){
 			var setting = {
		        async: {
		            enable: true,
		            url:"/tree/get",
		            autoParam:["id", "project", "level=lv", "dir=tmpdir"],
		            otherParam:{"dir":dir},
		            type: "post"
		        },
		        check: {
		            enable: true
		        },
		        view: {
		            dblClickExpand: false,
		            showLine: true,
		            selectedMulti: true
		        },
		        data: {
		            simpleData: {
		                enable:true,
		                idKey: "id",
		                pIdKey: "pId",
		                rootPId: "0"
		            }
		        },
		        callback: {
		            onCheck : function(event, treeId, treeNode){
		                var tmp = common.zTree.getCheckedNodes(true);
		                var res = new Array();
		                $.each(tmp, function(k, v) {
		                    console.log(v);
		                    var flag = v.check_Child_State;
		                    if(flag == -1 || flag == 2) {
		                      var tree = v.dir;
		                      res.push(tree);
		                    }
		                })

		                //将数据显示出来
		                var html = "";
		                $.each(res, function(k, v) {
		                    html += v + '\n';
		                })
		                $('#select_node').val(html);
		            },
		            onClick : function(event, treeId, treeNode){
		                var node =  common.zTree.getNodeByTId(treeNode.tId); 
		                common.zTree.checkNode(node);

		                var tmp = common.zTree.getCheckedNodes(true);
		                var res = new Array();
		                $.each(tmp, function(k, v) {
		                    console.log(v);
		                    var flag = v.check_Child_State;
		                    if(flag == -1 || flag == 2) {
		                      var tree = v.dir;
		                      res.push(tree);
		                    }
		                })

		                //将数据显示出来
		                var html = "";
		                $.each(res, function(k, v) {
		                    html += v + '\n';
		                })
		                $('#select_node').val(html);
		            }
		        }
		    };

			var t = $("#tree");
			common.zTree = $.fn.zTree.init(t, setting);
	        setTimeout(function(){
	          var root = common.zTree.getNodeByTId('tree_1');
	          common.zTree.expandNode(root);
	        }, 1000);
 		} else {
 			//显示添加项目的弹窗
 			$('#add_subject').modal('show');
 		}
 	}
 }